package com.jk.controller.admin;

import com.jk.controller.BaseController;
import com.jk.model.User;
import com.jk.service.UserService;
import com.jk.util.SessionUtil;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 登录
 * Created by JK on 2017/1/24.
 */
@Controller
@RequestMapping("/admin/login")
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping
    public String toLogin() {
        return "/admin/login";
    }

    /**
     * 用户登陆
     * 先根据用户名查询出一条用户记录再对比密码是否正确可以防止sql注入
     * @param username  用户名
     * @param password  密码
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> login(String username, String password){
        try {
            log.debug("用户登陆参数! username = {}, password = {}", username, SecureUtil.md5().digestHex(password));
            User user = userService.findByUserName(username);
            if(null == user){
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            if(!SecureUtil.md5().digestHex(password).equals(user.getPassword())){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
            setSession(SessionUtil.SESSION_ADMIN, user);
            log.info("用户登陆成功! user = {}", user);
            return ResponseEntity.ok(null);
        } catch (Exception e) {
            log.error("用户登陆错误! username = {}, password = {}, e = {}", username, SecureUtil.md5().digestHex(password), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping(value = "/out")
    public String loginOut(){
        removeSession(SessionUtil.SESSION_ADMIN);
        return "redirect:/admin/login";
    }

}
